﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace JY.Label
{
    /// <summary>
    /// 标签命令转换
    /// </summary>
    public static class LabelCmdConverter
    {
        #region # 根据标签数据将打印模板转换打印命令——string LabelDataConvert(this string labelCommandTemplate, LabelData labelData)
        /// <summary>
        /// 根据标签数据将打印模板转换打印命令
        /// </summary>
        /// <param name="labelCommandTemplate">打印模板</param>
        /// <param name="labelData">标签数据</param>
        /// <returns>返回转换结果。Key 是否转换成功  value转换结果</returns>
        public static KeyValuePair<bool, string> LabelDataConvert(this string labelCommandTemplate, LabelData labelData)
        {
            string labelCommand = labelCommandTemplate;
            if (labelData == null)
            {
                return new KeyValuePair<bool, string>(false, labelCommand);
            }
            PropertyInfo[] properties = labelData.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

            if (properties.Length <= 0)
            {
                return new KeyValuePair<bool, string>(false, labelCommand);
            }

            foreach (PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(labelData, null);
                if (value == null) continue;
                labelCommand = labelCommand.Replace("{{" + name + "}}", value.ToString());
            }
            return new KeyValuePair<bool, string>(true, labelCommand);
        }
        #endregion

        #region # 根据标签数据将打印模板转换打印命令——string LabelDataDicConvert(this string labelCommandTemplate, Dictionary<string,string> labelDataDic)
        /// <summary>
        /// 根据标签数据字典将打印模板转换打印命令
        /// </summary>
        /// <param name="labelCommandTemplate">打印模板</param>
        /// <param name="labelDataDic">标签数据</param>
        /// <returns>返回转换结果。Key 是否转换成功  value转换结果</returns>
        public static KeyValuePair<bool,string> LabelDataDicConvert(this string labelCommandTemplate, Dictionary<string,string> labelDataDic)
        {
            string labelCommand = labelCommandTemplate;
            if (labelDataDic == null||!labelDataDic.Any())
            {
                return new KeyValuePair<bool, string>(false, labelCommand);
            }

            foreach (var labelData in labelDataDic)
            {
                labelCommand = labelCommand.Replace("{{" + labelData.Key + "}}", labelData.Value);
            }
            return new KeyValuePair<bool, string>(true, labelCommand);
        }
        #endregion
    }
}
